<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生作业管理系统</title>
    <script src="https://unpkg.com/quagga@0.12.1/dist/quagga.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .main-content {
            padding: 30px;
        }

        .tabs {
            display: flex;
            margin-bottom: 30px;
            border-bottom: 2px solid #eee;
        }

        .tab {
            padding: 15px 30px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 1.1em;
            color: #666;
            transition: all 0.3s;
        }

        .tab.active {
            color: #4facfe;
            border-bottom: 3px solid #4facfe;
        }

        .tab:hover {
            background: #f8f9fa;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .scanner-section {
            text-align: center;
            margin-bottom: 30px;
        }

        #scanner-container {
            position: relative;
            width: 100%;
            max-width: 600px;
            margin: 0 auto;
            background: #000;
            border-radius: 10px;
            overflow: hidden;
        }

        #scanner-container video {
            width: 100%;
            height: auto;
        }

        .scanner-overlay {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 200px;
            height: 100px;
            border: 2px solid #4facfe;
            border-radius: 10px;
            background: rgba(79, 172, 254, 0.1);
        }

        .scanner-overlay::before {
            content: '';
            position: absolute;
            top: -2px;
            left: -2px;
            right: -2px;
            bottom: -2px;
            border: 2px solid #4facfe;
            border-radius: 10px;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .controls {
            margin: 20px 0;
        }

        .btn {
            padding: 12px 30px;
            margin: 0 10px;
            border: none;
            border-radius: 25px;
            font-size: 1.1em;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        .student-list {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
        }

        .student-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            margin: 10px 0;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .student-info {
            display: flex;
            align-items: center;
        }

        .student-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-right: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 1.2em;
        }

        .student-details h3 {
            margin-bottom: 5px;
            color: #333;
        }

        .student-details p {
            color: #666;
            font-size: 0.9em;
        }

        .status {
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 0.9em;
        }

        .status.completed {
            background: #d4edda;
            color: #155724;
        }

        .status.pending {
            background: #f8d7da;
            color: #721c24;
        }

        .status-time {
            margin-left: 10px;
            font-size: 0.8em;
            color: #666;
        }

        .message {
            padding: 15px;
            margin: 20px 0;
            border-radius: 8px;
            text-align: center;
            font-weight: bold;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }

        .stat-number {
            font-size: 2.5em;
            font-weight: bold;
            color: #4facfe;
            margin-bottom: 10px;
        }

        .stat-label {
            color: #666;
            font-size: 1.1em;
        }

        .filter-controls {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .filter-btn {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .filter-btn.active {
            background: #4facfe;
            color: white;
            border-color: #4facfe;
        }

        .date-filter {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
        }

        .date-filter label {
            font-weight: bold;
            color: #333;
        }

        .date-filter input[type="date"] {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1em;
        }

        .history-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .history-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 800px;
            max-height: 80vh;
            overflow-y: auto;
            position: relative;
        }

        .history-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .history-stat-card {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }

        .history-stat-number {
            font-size: 1.8em;
            font-weight: bold;
            color: #4facfe;
        }

        .history-stat-label {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }

        .history-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .history-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            margin: 5px 0;
            background: white;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .history-date {
            font-weight: bold;
            color: #333;
        }

        .history-details {
            font-size: 0.9em;
            color: #666;
        }

        .student-form {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1em;
        }

        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 2px rgba(79, 172, 254, 0.2);
        }

        .form-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .btn-small {
            padding: 6px 12px;
            font-size: 0.9em;
            border-radius: 15px;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-warning:hover {
            background: #e0a800;
            transform: translateY(-1px);
        }

        .barcode-display {
            text-align: center;
            margin: 20px 0;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .barcode-display svg {
            max-width: 100%;
            height: auto;
        }

        .student-management-list {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
        }

        .student-management-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            margin: 10px 0;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .student-management-info {
            flex: 1;
        }

        .student-management-actions {
            display: flex;
            gap: 10px;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 500px;
            position: relative;
        }

        .close {
            position: absolute;
            right: 20px;
            top: 15px;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #aaa;
        }

        .close:hover {
            color: #000;
        }

        .search-box {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-bottom: 20px;
            font-size: 1em;
        }

        .search-box:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 2px rgba(79, 172, 254, 0.2);
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }
            
            .header {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 2em;
            }
            
            .main-content {
                padding: 20px;
            }
            
            .tabs {
                flex-direction: column;
            }
            
            .tab {
                text-align: center;
                padding: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>学生作业管理系统</h1>
            <p>扫描条形码，记录学生作业完成情况</p>
        </div>

        <div class="main-content">
            <div class="tabs">
                <button class="tab active" onclick="switchTab('scan')">扫描作业</button>
                <button class="tab" onclick="switchTab('students')">学生列表</button>
                <button class="tab" onclick="switchTab('management')">学生管理</button>
                <button class="tab" onclick="switchTab('stats')">统计报表</button>
            </div>

            <div id="scan-tab" class="tab-content active">
                <div class="scanner-section">
                    <h2>扫描学生作业条形码</h2>
                    <div id="scanner-container">
                        <div id="interactive" class="viewport"></div>
                        <div class="scanner-overlay"></div>
                    </div>
                    <div class="controls">
                        <button class="btn btn-primary" onclick="startScanner()">开始扫描</button>
                        <button class="btn btn-secondary" onclick="stopScanner()">停止扫描</button>
                    </div>
                    <div id="scan-message"></div>
                </div>
            </div>

            <div id="students-tab" class="tab-content">
                <h2>学生作业情况</h2>
                <div class="date-filter">
                    <label for="date-select">查询日期：</label>
                    <input type="date" id="date-select" onchange="loadStudentsByDate()">
                    <button class="btn btn-primary btn-small" onclick="setToday()">今天</button>
                    <button class="btn btn-secondary btn-small" onclick="showHistoryRecords()">历史记录</button>
                </div>
                <div class="filter-controls">
                    <button class="filter-btn active" onclick="filterStudents('all')">全部学生</button>
                    <button class="filter-btn" onclick="filterStudents('pending')">未完成</button>
                    <button class="filter-btn" onclick="filterStudents('completed')">已完成</button>
                </div>
                <div id="students-list" class="student-list"></div>
            </div>

            <div id="management-tab" class="tab-content">
                <h2>学生管理</h2>
                <div class="student-form">
                    <h3 id="form-title">添加新学生</h3>
                    <form id="student-form">
                        <div class="form-group">
                            <label for="student-name">学生姓名:</label>
                            <input type="text" id="student-name" required>
                        </div>
                        <div class="form-group">
                            <label for="student-id">学号:</label>
                            <input type="text" id="student-id" required>
                        </div>
                        <div class="form-group">
                            <label for="student-class">班级:</label>
                            <input type="text" id="student-class" required>
                        </div>
                        <div class="form-group">
                            <label for="student-barcode">条形码:</label>
                            <div style="display: flex; gap: 10px; align-items: center;">
                                <input type="text" id="student-barcode" placeholder="留空自动生成" readonly>
                                <button type="button" class="btn btn-secondary btn-small" onclick="toggleBarcodeInput()">手动输入</button>
                                <button type="button" class="btn btn-primary btn-small" onclick="scanBarcodeForStudent()">扫码输入</button>
                            </div>
                            <div id="barcode-scanner-container" style="display: none; margin-top: 10px;">
                                <div id="student-barcode-scanner" style="position: relative; width: 100%; max-width: 400px; margin: 0 auto; background: #000; border-radius: 10px; overflow: hidden;">
                                    <div id="student-interactive" class="viewport"></div>
                                    <div class="scanner-overlay"></div>
                                </div>
                                <div style="text-align: center; margin-top: 10px;">
                                    <button type="button" class="btn btn-secondary btn-small" onclick="stopStudentBarcodeScanner()">停止扫描</button>
                                </div>
                                <div style="text-align: center; margin-top: 10px; font-size: 0.9em; color: #666;">
                                    <p>如果扫描不成功，可以尝试：</p>
                                    <p>1. 调整光线和距离</p>
                                    <p>2. 确保条形码清晰可见</p>
                                    <p>3. <a href="#" onclick="showManualInput(); return false;" style="color: #4facfe; text-decoration: none;">手动输入条形码</a></p>
                                </div>
                            </div>
                            <div id="barcode-manual-input" style="display: none; margin-top: 10px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                                <h4>手动输入条形码</h4>
                                <p style="font-size: 0.9em; color: #666; margin-bottom: 10px;">
                                    如果扫描无法识别，请手动输入条形码数字：
                                </p>
                                <div style="display: flex; gap: 10px;">
                                    <input type="text" id="manual-barcode-input" placeholder="请输入条形码数字" style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                                    <button type="button" class="btn btn-primary btn-small" onclick="applyManualBarcode()">应用</button>
                                    <button type="button" class="btn btn-secondary btn-small" onclick="cancelManualInput()">取消</button>
                                </div>
                            </div>
                        </div>
                        <div class="form-actions">
                            <button type="button" class="btn btn-secondary" onclick="resetForm()">重置</button>
                            <button type="submit" class="btn btn-primary">保存学生</button>
                        </div>
                    </form>
                </div>
                
                <div class="student-management-list">
                    <h3>学生列表</h3>
                    <input type="text" class="search-box" placeholder="搜索学生姓名或学号..." onkeyup="searchStudents(this.value)">
                    <div id="management-students-list"></div>
                </div>
            </div>

            <div id="stats-tab" class="tab-content">
                <h2>作业统计</h2>
                <div class="stats">
                    <div class="stat-card">
                        <div class="stat-number" id="total-students">0</div>
                        <div class="stat-label">总学生数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="completed-today">0</div>
                        <div class="stat-label">今日完成</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="pending-today">0</div>
                        <div class="stat-label">待完成</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="completion-rate">0%</div>
                        <div class="stat-label">完成率</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 历史记录模态框 -->
    <div id="history-modal" class="history-modal">
        <div class="history-content">
            <span class="close" onclick="closeHistoryModal()">&times;</span>
            <h2>作业历史记录</h2>
            <div class="history-stats" id="history-stats"></div>
            <div class="history-list" id="history-list"></div>
        </div>
    </div>

    <!-- 条形码显示模态框 -->
    <div id="barcode-modal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeBarcodeModal()">&times;</span>
            <h2>学生条形码</h2>
            <div class="student-info">
                <h3 id="barcode-student-name"></h3>
                <p>条形码: <span id="barcode-number"></span></p>
            </div>
            <div class="barcode-display">
                <div id="barcode-container"></div>
            </div>
            <div class="form-actions">
                <button class="btn btn-secondary" onclick="closeBarcodeModal()">关闭</button>
                <button class="btn btn-primary" onclick="printBarcode()">打印条形码</button>
            </div>
        </div>
    </div>

    <script>
        // 学生数据
        let students = JSON.parse(localStorage.getItem('students')) || [
            { id: '001', name: '张三', className: '三年级一班', barcode: '1234567890123' },
            { id: '002', name: '李四', className: '三年级一班', barcode: '1234567890124' },
            { id: '003', name: '王五', className: '三年级一班', barcode: '1234567890125' },
            { id: '004', name: '赵六', className: '三年级一班', barcode: '1234567890126' },
            { id: '005', name: '钱七', className: '三年级一班', barcode: '1234567890127' },
            { id: '006', name: '孙八', className: '三年级一班', barcode: '1234567890128' }
        ];

        // 当前编辑的学生ID
        let editingStudentId = null;

        // 作业记录
        let homeworkRecords = JSON.parse(localStorage.getItem('homeworkRecords')) || {};

        // 扫描器状态
        let scannerActive = false;
        let studentScannerActive = false;
        let isManualInput = false;

        // 初始化页面
        function init() {
            saveStudents();
            // 设置今天为默认日期
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('date-select').value = today;
            loadStudents();
            updateStats();
            generateNewBarcode();
        }

        // 切换标签页
        function switchTab(tabName) {
            // 移除所有活动状态
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            
            // 激活当前标签页
            event.target.classList.add('active');
            document.getElementById(tabName + '-tab').classList.add('active');
            
            // 如果切换到学生列表，刷新数据
            if (tabName === 'students') {
                loadStudents();
            } else if (tabName === 'management') {
                loadManagementStudents();
            } else if (tabName === 'stats') {
                updateStats();
            }
        }

        // 开始扫描
        function startScanner() {
            if (scannerActive) return;
            
            const scannerContainer = document.getElementById('scanner-container');
            
            Quagga.init({
                inputStream: {
                    name: "Live",
                    type: "LiveStream",
                    target: scannerContainer,
                    constraints: {
                        width: { ideal: 640 },
                        height: { ideal: 480 },
                        facingMode: "environment",
                        aspectRatio: 4/3
                    },
                    area: {
                        top: "0%",
                        right: "0%",
                        left: "0%",
                        bottom: "0%"
                    }
                },
                locator: {
                    patchSize: "medium",
                    halfSample: true
                },
                numOfWorkers: 2,
                decoder: {
                    readers: [
                        "code_128_reader",
                        "ean_reader",
                        "ean_8_reader",
                        "code_39_reader",
                        "code_39_vin_reader",
                        "codabar_reader",
                        "upc_reader",
                        "upc_e_reader"
                    ],
                    debug: {
                        showCanvas: true,
                        showPatches: true,
                        showFoundPatches: true,
                        showSkeleton: true,
                        showLabels: true,
                        showPatchLabels: true,
                        showRemainingPatchLabels: true,
                        boxFromPatches: {
                            showTransformed: true,
                            showTransformedBox: true,
                            showBB: true
                        }
                    }
                },
                locate: true
            }, function(err) {
                if (err) {
                    console.log('摄像头初始化错误:', err);
                    showMessage('无法启动摄像头，请检查权限设置或尝试刷新页面', 'error');
                    return;
                }
                console.log("扫描器初始化完成");
                Quagga.start();
                scannerActive = true;
                showMessage('摄像头已启动，请将条形码对准扫描区域', 'success');
            });

            // 监听扫描结果
            Quagga.onDetected(function(result) {
                console.log('扫描结果:', result);
                const barcode = result.codeResult.code;
                processBarcode(barcode);
            });

            // 监听处理过程
            Quagga.onProcessed(function(result) {
                const drawingCtx = Quagga.canvas.ctx.overlay;
                const canvas = Quagga.canvas.dom.overlay;
                
                if (result) {
                    if (result.boxes) {
                        drawingCtx.clearRect(0, 0, canvas.width, canvas.height);
                        result.boxes.filter(function (box) {
                            return box !== result.box;
                        }).forEach(function (box) {
                            Quagga.ImageDebug.drawPath(box, {x: 0, y: 1}, drawingCtx, {color: "green", lineWidth: 2});
                        });
                    }
                    
                    if (result.box) {
                        Quagga.ImageDebug.drawPath(result.box, {x: 0, y: 1}, drawingCtx, {color: "blue", lineWidth: 2});
                    }
                    
                    if (result.codeResult && result.codeResult.code) {
                        Quagga.ImageDebug.drawPath(result.line, {x: 'x', y: 'y'}, drawingCtx, {color: "red", lineWidth: 3});
                    }
                }
            });
        }

        // 停止扫描
        function stopScanner() {
            if (!scannerActive) return;
            
            Quagga.stop();
            scannerActive = false;
            showMessage('扫描已停止', 'success');
        }

        // 处理条形码
        function processBarcode(barcode) {
            const student = students.find(s => s.barcode === barcode);
            
            if (student) {
                const today = new Date().toISOString().split('T')[0];
                const recordKey = `${student.id}_${today}`;
                
                if (!homeworkRecords[recordKey]) {
                    homeworkRecords[recordKey] = {
                        studentId: student.id,
                        studentName: student.name,
                        date: today,
                        completedAt: new Date().toISOString(),
                        barcode: barcode
                    };
                    
                    // 保存到本地存储
                    localStorage.setItem('homeworkRecords', JSON.stringify(homeworkRecords));
                    
                    showMessage(`${student.name} 的作业已记录完成！`, 'success');
                    
                    // 播放成功音效（如果浏览器支持）
                    playSuccessSound();
                    
                    // 刷新学生列表和统计
                    loadStudents();
                    updateStats();
                } else {
                    showMessage(`${student.name} 的作业今天已经记录过了`, 'error');
                }
            } else {
                showMessage('未找到对应的学生信息，请先在学生管理中添加该学生', 'error');
            }
        }

        // 播放成功音效
        function playSuccessSound() {
            // 创建简单的提示音
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.frequency.value = 800;
            oscillator.type = 'sine';
            
            gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
            
            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.3);
        }

        // 显示消息
        function showMessage(message, type) {
            const messageDiv = document.getElementById('scan-message');
            messageDiv.innerHTML = `<div class="message ${type}">${message}</div>`;
            
            setTimeout(() => {
                messageDiv.innerHTML = '';
            }, 3000);
        }

        // 加载学生列表
        function loadStudents() {
            const selectedDate = document.getElementById('date-select').value;
            loadStudentsByDate(selectedDate);
        }

        // 根据日期加载学生列表
        function loadStudentsByDate(selectedDate) {
            const studentsList = document.getElementById('students-list');
            const date = selectedDate || new Date().toISOString().split('T')[0];
            
            // 如果没有选择日期，设置为今天
            if (!selectedDate) {
                document.getElementById('date-select').value = date;
            }
            
            let html = '';
            students.forEach(student => {
                const recordKey = `${student.id}_${date}`;
                const record = homeworkRecords[recordKey];
                const isCompleted = !!record;
                
                html += `
                    <div class="student-item" data-status="${isCompleted ? 'completed' : 'pending'}">
                        <div class="student-info">
                            <div class="student-avatar">${student.name.charAt(0)}</div>
                            <div class="student-details">
                                <h3>${student.name}</h3>
                                <p>学号: ${student.id} | 班级: ${student.className}</p>
                                <p>条形码: ${student.barcode}</p>
                            </div>
                        </div>
                        <div class="status ${isCompleted ? 'completed' : 'pending'}">
                            ${isCompleted ? '已完成' : '待完成'}
                            ${isCompleted ? `<span class="status-time">${new Date(record.completedAt).toLocaleTimeString()}</span>` : ''}
                        </div>
                    </div>
                `;
            });
            
            studentsList.innerHTML = html;
        }

        // 设置为今天
        function setToday() {
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('date-select').value = today;
            loadStudentsByDate(today);
        }

        // 显示历史记录
        function showHistoryRecords() {
            const modal = document.getElementById('history-modal');
            modal.style.display = 'block';
            loadHistoryStats();
            loadHistoryList();
        }

        // 关闭历史记录模态框
        function closeHistoryModal() {
            document.getElementById('history-modal').style.display = 'none';
        }

        // 加载历史统计
        function loadHistoryStats() {
            const statsContainer = document.getElementById('history-stats');
            
            // 计算统计数据
            const records = Object.values(homeworkRecords);
            const totalRecords = records.length;
            const uniqueStudents = new Set(records.map(r => r.studentId)).size;
            const uniqueDates = new Set(records.map(r => r.date)).size;
            
            // 计算最近7天的完成率
            const last7Days = [];
            for (let i = 6; i >= 0; i--) {
                const date = new Date();
                date.setDate(date.getDate() - i);
                const dateStr = date.toISOString().split('T')[0];
                last7Days.push(dateStr);
            }
            
            let last7DaysCompleted = 0;
            let last7DaysTotal = students.length * 7;
            
            last7Days.forEach(date => {
                students.forEach(student => {
                    const recordKey = `${student.id}_${date}`;
                    if (homeworkRecords[recordKey]) {
                        last7DaysCompleted++;
                    }
                });
            });
            
            const last7DaysRate = last7DaysTotal > 0 ? Math.round((last7DaysCompleted / last7DaysTotal) * 100) : 0;
            
            statsContainer.innerHTML = `
                <div class="history-stat-card">
                    <div class="history-stat-number">${totalRecords}</div>
                    <div class="history-stat-label">总记录数</div>
                </div>
                <div class="history-stat-card">
                    <div class="history-stat-number">${uniqueStudents}</div>
                    <div class="history-stat-label">参与学生</div>
                </div>
                <div class="history-stat-card">
                    <div class="history-stat-number">${uniqueDates}</div>
                    <div class="history-stat-label">记录天数</div>
                </div>
                <div class="history-stat-card">
                    <div class="history-stat-number">${last7DaysRate}%</div>
                    <div class="history-stat-label">近7天完成率</div>
                </div>
            `;
        }

        // 加载历史列表
        function loadHistoryList() {
            const listContainer = document.getElementById('history-list');
            
            // 按日期分组记录
            const recordsByDate = {};
            Object.values(homeworkRecords).forEach(record => {
                if (!recordsByDate[record.date]) {
                    recordsByDate[record.date] = [];
                }
                recordsByDate[record.date].push(record);
            });
            
            // 按日期排序（最新的在前）
            const sortedDates = Object.keys(recordsByDate).sort((a, b) => b.localeCompare(a));
            
            let html = '';
            sortedDates.forEach(date => {
                const records = recordsByDate[date];
                const completedCount = records.length;
                const totalCount = students.length;
                const completionRate = Math.round((completedCount / totalCount) * 100);
                
                html += `
                    <div class="history-item">
                        <div>
                            <div class="history-date">${formatDate(date)}</div>
                            <div class="history-details">
                                完成: ${completedCount}/${totalCount} (${completionRate}%)
                                | 平均完成时间: ${getAverageCompletionTime(records)}
                            </div>
                        </div>
                        <div>
                            <button class="btn btn-primary btn-small" onclick="viewDateDetails('${date}')">查看详情</button>
                        </div>
                    </div>
                `;
            });
            
            if (html === '') {
                html = '<div style="text-align: center; color: #666; padding: 20px;">暂无历史记录</div>';
            }
            
            listContainer.innerHTML = html;
        }

        // 格式化日期
        function formatDate(dateStr) {
            const date = new Date(dateStr);
            const today = new Date();
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            
            if (dateStr === today.toISOString().split('T')[0]) {
                return '今天';
            } else if (dateStr === yesterday.toISOString().split('T')[0]) {
                return '昨天';
            } else {
                return date.toLocaleDateString('zh-CN', {
                    month: 'long',
                    day: 'numeric',
                    weekday: 'long'
                });
            }
        }

        // 获取平均完成时间
        function getAverageCompletionTime(records) {
            if (records.length === 0) return '无数据';
            
            const times = records.map(r => new Date(r.completedAt).toLocaleTimeString());
            // 简化显示，返回第一个记录的时间作为示例
            return times[0];
        }

        // 查看某天详情
        function viewDateDetails(date) {
            // 切换到学生列表页面并设置日期
            document.getElementById('date-select').value = date;
            closeHistoryModal();
            switchTab('students');
            loadStudentsByDate(date);
        }

        // 筛选学生
        function filterStudents(status) {
            // 更新按钮状态
            document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');
            
            // 筛选学生项目
            const studentItems = document.querySelectorAll('.student-item');
            studentItems.forEach(item => {
                if (status === 'all') {
                    item.style.display = 'flex';
                } else {
                    item.style.display = item.dataset.status === status ? 'flex' : 'none';
                }
            });
        }

        // 更新统计数据
        function updateStats() {
            const today = new Date().toISOString().split('T')[0];
            let completedCount = 0;
            
            students.forEach(student => {
                const recordKey = `${student.id}_${today}`;
                if (homeworkRecords[recordKey]) {
                    completedCount++;
                }
            });
            
            const totalCount = students.length;
            const pendingCount = totalCount - completedCount;
            const completionRate = totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0;
            
            document.getElementById('total-students').textContent = totalCount;
            document.getElementById('completed-today').textContent = completedCount;
            document.getElementById('pending-today').textContent = pendingCount;
            document.getElementById('completion-rate').textContent = completionRate + '%';
        }

        // 保存学生数据
        function saveStudents() {
            localStorage.setItem('students', JSON.stringify(students));
        }

        // 生成新的条形码
        function generateNewBarcode() {
            const timestamp = Date.now();
            const random = Math.floor(Math.random() * 1000);
            const barcode = 'STU' + timestamp.toString().slice(-8) + random.toString().padStart(3, '0');
            document.getElementById('student-barcode').value = barcode;
        }

        // 重置表单
        function resetForm() {
            document.getElementById('student-form').reset();
            editingStudentId = null;
            document.getElementById('form-title').textContent = '添加新学生';
            generateNewBarcode();
        }

  
        // 加载管理页面学生列表
        function loadManagementStudents() {
            const managementList = document.getElementById('management-students-list');
            
            let html = '';
            students.forEach(student => {
                html += `
                    <div class="student-management-item">
                        <div class="student-management-info">
                            <h4>${student.name}</h4>
                            <p>学号: ${student.id} | 班级: ${student.className}</p>
                            <p>条形码: ${student.barcode}</p>
                        </div>
                        <div class="student-management-actions">
                            <button class="btn btn-warning btn-small" onclick="editStudent('${student.id}')">编辑</button>
                            <button class="btn btn-danger btn-small" onclick="deleteStudent('${student.id}')">删除</button>
                            <button class="btn btn-primary btn-small" onclick="showBarcode('${student.barcode}', '${student.name}')">查看条形码</button>
                        </div>
                    </div>
                `;
            });
            
            managementList.innerHTML = html;
        }

        // 编辑学生
        function editStudent(studentId) {
            const student = students.find(s => s.id === studentId);
            if (!student) return;
            
            editingStudentId = studentId;
            document.getElementById('form-title').textContent = '编辑学生信息';
            document.getElementById('student-name').value = student.name;
            document.getElementById('student-id').value = student.id;
            document.getElementById('student-class').value = student.className;
            document.getElementById('student-barcode').value = student.barcode;
            
            // 滚动到表单
            document.querySelector('.student-form').scrollIntoView({ behavior: 'smooth' });
        }

        // 删除学生
        function deleteStudent(studentId) {
            if (!confirm('确定要删除这个学生吗？此操作不可撤销。')) {
                return;
            }
            
            students = students.filter(s => s.id !== studentId);
            saveStudents();
            loadManagementStudents();
            loadStudents();
            updateStats();
            
            alert('学生已删除');
        }

        // 搜索学生
        function searchStudents(searchTerm) {
            const studentItems = document.querySelectorAll('.student-management-item');
            const term = searchTerm.toLowerCase();
            
            studentItems.forEach(item => {
                const text = item.textContent.toLowerCase();
                item.style.display = text.includes(term) ? 'flex' : 'none';
            });
        }

        // 显示条形码
        function showBarcode(barcode, studentName) {
            const modal = document.getElementById('barcode-modal');
            const barcodeContainer = document.getElementById('barcode-container');
            
            // 清空容器
            barcodeContainer.innerHTML = '';
            
            // 创建条形码
            const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            JsBarcode(svg, barcode, {
                format: 'CODE128',
                width: 2,
                height: 100,
                displayValue: true
            });
            
            barcodeContainer.appendChild(svg);
            document.getElementById('barcode-student-name').textContent = studentName;
            document.getElementById('barcode-number').textContent = barcode;
            
            modal.style.display = 'block';
        }

        // 关闭模态框
        function closeBarcodeModal() {
            document.getElementById('barcode-modal').style.display = 'none';
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('barcode-modal');
            if (event.target === modal) {
                closeBarcodeModal();
            }
        }

        // 打印条形码
        function printBarcode() {
            const printContent = document.getElementById('barcode-modal').innerHTML;
            const printWindow = window.open('', '_blank');
            
            printWindow.document.write(`
                <html>
                <head>
                    <title>打印条形码</title>
                    <style>
                        body { font-family: Arial, sans-serif; text-align: center; padding: 20px; }
                        .barcode-display { margin: 20px 0; }
                        .student-info { margin-bottom: 20px; }
                    </style>
                </head>
                <body>
                    ${printContent}
                </body>
                </html>
            `);
            
            printWindow.document.close();
            printWindow.print();
        }

        // 切换条形码输入方式
        function toggleBarcodeInput() {
            const barcodeInput = document.getElementById('student-barcode');
            const toggleBtn = event.target;
            
            if (isManualInput) {
                // 切换回自动生成
                barcodeInput.readOnly = true;
                barcodeInput.placeholder = '留空自动生成';
                toggleBtn.textContent = '手动输入';
                toggleBtn.className = 'btn btn-secondary btn-small';
                generateNewBarcode();
            } else {
                // 切换到手动输入
                barcodeInput.readOnly = false;
                barcodeInput.placeholder = '请输入条形码';
                toggleBtn.textContent = '自动生成';
                toggleBtn.className = 'btn btn-primary btn-small';
                barcodeInput.value = '';
            }
            
            isManualInput = !isManualInput;
        }

        // 扫描条形码用于学生信息
        function scanBarcodeForStudent() {
            const scannerContainer = document.getElementById('barcode-scanner-container');
            
            if (studentScannerActive) {
                stopStudentBarcodeScanner();
                return;
            }
            
            scannerContainer.style.display = 'block';
            
            Quagga.init({
                inputStream: {
                    name: "StudentLive",
                    type: "LiveStream",
                    target: document.getElementById('student-barcode-scanner'),
                    constraints: {
                        width: { ideal: 400 },
                        height: { ideal: 300 },
                        facingMode: "environment",
                        aspectRatio: 4/3
                    },
                    area: {
                        top: "0%",
                        right: "0%",
                        left: "0%",
                        bottom: "0%"
                    }
                },
                locator: {
                    patchSize: "medium",
                    halfSample: true
                },
                numOfWorkers: 2,
                decoder: {
                    readers: [
                        "code_128_reader",
                        "ean_reader",
                        "ean_8_reader",
                        "code_39_reader",
                        "code_39_vin_reader",
                        "codabar_reader",
                        "upc_reader",
                        "upc_e_reader"
                    ],
                    debug: {
                        showCanvas: true,
                        showPatches: true,
                        showFoundPatches: true,
                        showSkeleton: true,
                        showLabels: true,
                        showPatchLabels: true,
                        showRemainingPatchLabels: true,
                        boxFromPatches: {
                            showTransformed: true,
                            showTransformedBox: true,
                            showBB: true
                        }
                    }
                },
                locate: true
            }, function(err) {
                if (err) {
                    console.log('学生条形码扫描器初始化错误:', err);
                    alert('无法启动摄像头，请检查权限设置或尝试刷新页面');
                    scannerContainer.style.display = 'none';
                    return;
                }
                console.log("学生条形码扫描器初始化完成");
                Quagga.start();
                studentScannerActive = true;
                
                // 更新按钮状态
                const scanBtn = document.querySelector('button[onclick="scanBarcodeForStudent()"]');
                scanBtn.textContent = '停止扫描';
                scanBtn.className = 'btn btn-danger btn-small';
                
                alert('摄像头已启动，请将条形码对准扫描区域');
            });

            // 监听扫描结果
            Quagga.onDetected(function(result) {
                console.log('学生条形码扫描结果:', result);
                const barcode = result.codeResult.code;
                processStudentBarcode(barcode);
            });

            // 监听处理过程
            Quagga.onProcessed(function(result) {
                const drawingCtx = Quagga.canvas.ctx.overlay;
                const canvas = Quagga.canvas.dom.overlay;
                
                if (result) {
                    if (result.boxes) {
                        drawingCtx.clearRect(0, 0, canvas.width, canvas.height);
                        result.boxes.filter(function (box) {
                            return box !== result.box;
                        }).forEach(function (box) {
                            Quagga.ImageDebug.drawPath(box, {x: 0, y: 1}, drawingCtx, {color: "green", lineWidth: 2});
                        });
                    }
                    
                    if (result.box) {
                        Quagga.ImageDebug.drawPath(result.box, {x: 0, y: 1}, drawingCtx, {color: "blue", lineWidth: 2});
                    }
                    
                    if (result.codeResult && result.codeResult.code) {
                        Quagga.ImageDebug.drawPath(result.line, {x: 'x', y: 'y'}, drawingCtx, {color: "red", lineWidth: 3});
                    }
                }
            });
        }

        // 停止学生条形码扫描
        function stopStudentBarcodeScanner() {
            if (!studentScannerActive) return;
            
            Quagga.stop();
            studentScannerActive = false;
            
            const scannerContainer = document.getElementById('barcode-scanner-container');
            scannerContainer.style.display = 'none';
            
            // 恢复按钮状态
            const scanBtn = document.querySelector('button[onclick="scanBarcodeForStudent()"]');
            scanBtn.textContent = '扫码输入';
            scanBtn.className = 'btn btn-primary btn-small';
        }

        // 处理学生条形码
        function processStudentBarcode(barcode) {
            console.log('处理条形码:', barcode);
            
            // 检查条形码是否已被使用
            const existingStudent = students.find(s => s.barcode === barcode && s.id !== editingStudentId);
            
            if (existingStudent) {
                alert(`该条形码已被学生 "${existingStudent.name}" 使用，请使用其他条形码`);
                return;
            }
            
            // 设置条形码到输入框
            document.getElementById('student-barcode').value = barcode;
            
            // 停止扫描
            stopStudentBarcodeScanner();
            
            // 切换到手动输入模式以便修改
            if (!isManualInput) {
                toggleBarcodeInput();
            }
            
            alert('条形码已成功录入！');
        }

        // 显示手动输入条形码界面
        function showManualInput() {
            document.getElementById('barcode-scanner-container').style.display = 'none';
            document.getElementById('barcode-manual-input').style.display = 'block';
            document.getElementById('manual-barcode-input').focus();
        }

        // 应用手动输入的条形码
        function applyManualBarcode() {
            const manualBarcode = document.getElementById('manual-barcode-input').value.trim();
            
            if (!manualBarcode) {
                alert('请输入条形码');
                return;
            }
            
            if (manualBarcode.length < 8) {
                alert('条形码长度不能少于8位');
                return;
            }
            
            // 检查条形码是否已被使用
            const existingStudent = students.find(s => s.barcode === manualBarcode && s.id !== editingStudentId);
            
            if (existingStudent) {
                alert(`该条形码已被学生 "${existingStudent.name}" 使用，请使用其他条形码`);
                return;
            }
            
            // 设置条形码到输入框
            document.getElementById('student-barcode').value = manualBarcode;
            
            // 停止扫描
            stopStudentBarcodeScanner();
            
            // 隐藏手动输入界面
            document.getElementById('barcode-manual-input').style.display = 'none';
            
            // 切换到手动输入模式以便修改
            if (!isManualInput) {
                toggleBarcodeInput();
            }
            
            alert('条形码已成功录入！');
        }

        // 取消手动输入
        function cancelManualInput() {
            document.getElementById('barcode-manual-input').style.display = 'none';
            document.getElementById('manual-barcode-input').value = '';
        }

        // 重置表单时重置输入状态
        function resetForm() {
            document.getElementById('student-form').reset();
            editingStudentId = null;
            document.getElementById('form-title').textContent = '添加新学生';
            
            // 重置输入状态
            if (isManualInput) {
                toggleBarcodeInput();
            }
            
            // 确保扫描器停止
            if (studentScannerActive) {
                stopStudentBarcodeScanner();
            }
            
            generateNewBarcode();
        }

        // 修改保存学生信息函数，添加条形码验证
        document.getElementById('student-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const name = document.getElementById('student-name').value.trim();
            const id = document.getElementById('student-id').value.trim();
            const className = document.getElementById('student-class').value.trim();
            let barcode = document.getElementById('student-barcode').value.trim();
            
            if (!name || !id || !className) {
                alert('请填写所有必填字段');
                return;
            }
            
            // 如果条形码为空，自动生成
            if (!barcode) {
                generateNewBarcode();
                barcode = document.getElementById('student-barcode').value;
            }
            
            // 验证条形码格式（简单验证）
            if (barcode.length < 8) {
                alert('条形码长度不能少于8位');
                return;
            }
            
            // 检查学号是否重复
            const existingStudent = students.find(s => s.id === id && s.id !== editingStudentId);
            if (existingStudent) {
                alert('学号已存在，请使用其他学号');
                return;
            }
            
            // 检查条形码是否重复
            const existingBarcode = students.find(s => s.barcode === barcode && s.id !== editingStudentId);
            if (existingBarcode) {
                alert('该条形码已被其他学生使用，请使用其他条形码');
                return;
            }
            
            if (editingStudentId) {
                // 编辑现有学生
                const studentIndex = students.findIndex(s => s.id === editingStudentId);
                if (studentIndex !== -1) {
                    students[studentIndex] = { id, name, className, barcode };
                }
            } else {
                // 添加新学生
                students.push({ id, name, className, barcode });
            }
            
            saveStudents();
            loadManagementStudents();
            loadStudents();
            updateStats();
            resetForm();
            
            alert(editingStudentId ? '学生信息已更新' : '学生添加成功');
        });

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>